package google

import (
	"encoding/json"
	"errors"
	"time"
	"video-api/utility/login_tool"
)

// Session 使用谷歌存储验证过程中的数据.
type Session struct {
	AuthURL      string
	AccessToken  string
	RefreshToken string
	ExpiresAt    time.Time
	IDToken      string
}

// GetAuthURL 将返回URL设置通过调用‘BeginAuth’的谷歌提供程序.
func (s *Session) GetAuthURL() (string, error) {
	if s.AuthURL == "" {
		return "", errors.New(login_tool.NoAuthUrlErrorMessage)
	}
	return s.AuthURL, nil
}

// Authorize 使用谷歌创建会话，并返回要存储以供将来使用的访问令牌.
func (s *Session) Authorize(provider login_tool.Provider, code string) (string, error) {
	p := provider.(*Provider)
	token, err := p.config.Exchange(login_tool.ContextForClient(p.Client()), code)
	if err != nil {
		return "", err
	}

	if !token.Valid() {
		return "", errors.New("Invalid token received from provider")
	}

	s.AccessToken = token.AccessToken
	s.RefreshToken = token.RefreshToken
	s.ExpiresAt = token.Expiry
	if idToken := token.Extra("id_token"); idToken != nil {
		s.IDToken = idToken.(string)
	}
	return token.AccessToken, err
}

// Marshal 换成字符串
func (s *Session) Marshal() string {
	b, _ := json.Marshal(s)
	return string(b)
}

func (s *Session) String() string {
	return s.Marshal()
}
